{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4c3bfe99",
   "metadata": {},
   "source": [
    "# 在 单-三重态量子比特系统中，采用不同脉冲数实现单量子比特任意门的计算结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "d1e131c3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mean of error is： 0.6272645430597421\n",
      "\n",
      "error_min_list:\n",
      " [0.26501825674997403, 0.9703480064140677, 0.46362872698125035, 0.9921292061365249, 0.14847172312148949, 0.8687930253120443, 0.27343269850037943, 0.8281934417617, 0.3429878258201977, 0.8462970834383421, 0.566951668143233, 0.8291968436540613, 0.469273761710431, 0.12838191137661747, 0.00571535245808108, 0.8672364525102665, 0.8927478380606465, 0.9028077610950185, 0.7837305248272066, 0.956468285694717, 0.11821511035252008, 0.0689915347784884, 0.952254833218876, 0.994922688607323, 0.4121172741003494, 0.9951391731723069, 0.9072755141340463, 0.8099442686456212, 0.3940456599880442, 0.8863070271255237, 0.8501585939366474, 0.281283306085752]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "error_min_list = [] # max of infid\n",
    "\n",
    "for i in range(len(u_mats)):\n",
    "    error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(eval_x, eval_y[i])]))\n",
    "    error_min_list.append(error)\n",
    "print('mean of error is：', np.mean(error_min_list))\n",
    "print('\\nerror_min_list:\\n', error_min_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "0f56a085",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "进度: 1/32  error_min: 0.24582932250260003 iter_num: 3999\n",
      "进度: 2/32  error_min: 0.6703344727374386 iter_num: 3999\n",
      "进度: 3/32  error_min: 0.4496484743380629 iter_num: 3999\n",
      "进度: 4/32  error_min: 0.6598928165176515 iter_num: 3999\n",
      "进度: 5/32  error_min: 0.09700271739685162 iter_num: 3999\n",
      "进度: 6/32  error_min: 0.5722075611926492 iter_num: 3999\n",
      "进度: 7/32  error_min: 0.24415761576134842 iter_num: 3999\n",
      "进度: 8/32  error_min: 0.23960486978034334 iter_num: 3999\n",
      "进度: 9/32  error_min: 0.32138613797941495 iter_num: 3999\n",
      "进度: 10/32  error_min: 0.407950071870291 iter_num: 3999\n",
      "进度: 11/32  error_min: 0.5621627145242204 iter_num: 3999\n",
      "进度: 12/32  error_min: 0.6943971131031069 iter_num: 3999\n",
      "进度: 13/32  error_min: 0.6494657765758315 iter_num: 3999\n",
      "进度: 14/32  error_min: 0.023259309046758325 iter_num: 3999\n",
      "进度: 15/32  error_min: 0.004080187458626483 iter_num: 3999\n",
      "进度: 16/32  error_min: 0.5236322666148397 iter_num: 3999\n",
      "进度: 17/32  error_min: 0.36685038196109476 iter_num: 3999\n",
      "进度: 18/32  error_min: 0.008555692058092257 iter_num: 3999\n",
      "进度: 19/32  error_min: 0.5962608219902648 iter_num: 3999\n",
      "进度: 20/32  error_min: 0.5161135257492956 iter_num: 3999\n",
      "进度: 21/32  error_min: 0.1053102235197495 iter_num: 3999\n",
      "进度: 22/32  error_min: 0.04863102247927065 iter_num: 3999\n",
      "进度: 23/32  error_min: 0.370055873766597 iter_num: 3999\n",
      "进度: 24/32  error_min: 0.5740057087088446 iter_num: 3999\n",
      "进度: 25/32  error_min: 0.41264513472117803 iter_num: 3999\n",
      "进度: 26/32  error_min: 0.043294431378029685 iter_num: 3999\n",
      "进度: 27/32  error_min: 0.8415489519056027 iter_num: 3999\n",
      "进度: 28/32  error_min: 0.517374560418077 iter_num: 3999\n",
      "进度: 29/32  error_min: 0.13640037072655053 iter_num: 3999\n",
      "进度: 30/32  error_min: 0.6949718677180237 iter_num: 3999\n",
      "进度: 31/32  error_min: 0.3714213034520535 iter_num: 3999\n",
      "进度: 32/32  error_min: 0.11179302807784364 iter_num: 3999\n",
      "mean of iter_num: 3999.0\n",
      "\n",
      " mean of error is： 0.37750763518845637\n",
      "\n",
      "error_min_list:\n",
      " [0.24582932250260003, 0.6703344727374386, 0.4496484743380629, 0.6598928165176515, 0.09700271739685162, 0.5722075611926492, 0.24415761576134842, 0.23960486978034334, 0.32138613797941495, 0.407950071870291, 0.5621627145242204, 0.6943971131031069, 0.6494657765758315, 0.023259309046758325, 0.004080187458626483, 0.5236322666148397, 0.36685038196109476, 0.008555692058092257, 0.5962608219902648, 0.5161135257492956, 0.1053102235197495, 0.04863102247927065, 0.370055873766597, 0.5740057087088446, 0.41264513472117803, 0.043294431378029685, 0.8415489519056027, 0.517374560418077, 0.13640037072655053, 0.6949718677180237, 0.3714213034520535, 0.11179302807784364]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi/2\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "# circ += gate_0('01').on(0)\n",
    "# circ += gate_0('02').on(0)\n",
    "# circ += gate_0('03').on(0)\n",
    "# circ += gate_0('04').on(0)\n",
    "# circ += gate_0('05').on(0)\n",
    "# circ += gate_0('06').on(0)\n",
    "# circ += gate_0('07').on(0)\n",
    "# circ += gate_0('08').on(0)\n",
    "# circ += gate_0('09').on(0)\n",
    "\n",
    "# circ += gate_0('10').on(0)\n",
    "# circ += gate_0('11').on(0)\n",
    "# circ += gate_0('12').on(0)\n",
    "# circ += gate_0('13').on(0)\n",
    "# circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "\n",
    "error_min_list = [] \n",
    "m_list = []\n",
    "lr = 0.05\n",
    "for i in range(len(u_mats)):\n",
    "    Quantum_net = MQLayer(grad_ops)\n",
    "    opti = Adam(Quantum_net.trainable_params(), learning_rate=lr)  \n",
    "    net = TrainOneStepCell(Quantum_net, opti)\n",
    "    error_min = 1\n",
    "    for j in range(len(train_x)):\n",
    "        net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "        params = abs(Quantum_net.weight.asnumpy())\n",
    "        final_state = []\n",
    "        for k in range(100): # 100 个测试点\n",
    "            sim.reset()\n",
    "            sim.set_qs(eval_x[k])\n",
    "            sim.apply_circuit(circ, params)\n",
    "            final_state.append(sim.get_qs())\n",
    "        error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "        error_min = min(error, error_min)\n",
    "        if error_min < 1e-5:\n",
    "            break\n",
    "    error_min_list.append(error_min)\n",
    "    m_list.append(j)\n",
    "    print(f\"进度: {i+1}/{len(u_mats)} \", 'error_min:', error_min, 'iter_num:', j)\n",
    "    \n",
    "print('mean of iter_num:', np.mean(m_list))\n",
    "print('\\n mean of error is：', np.mean(error_min_list))\n",
    "print('\\nerror_min_list:\\n', error_min_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "68da9538",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "进度: 1/32  error_min: 0.18778399892822117 iter_num: 3999\n",
      "进度: 2/32  error_min: 0.15605287245380872 iter_num: 3999\n",
      "进度: 3/32  error_min: 0.2736579900172741 iter_num: 3999\n",
      "进度: 4/32  error_min: 0.5503106382610887 iter_num: 3999\n",
      "进度: 5/32  error_min: 0.0469588441893376 iter_num: 3999\n",
      "进度: 6/32  error_min: 0.14476512760846094 iter_num: 3999\n",
      "进度: 7/32  error_min: 0.13597629865733019 iter_num: 3999\n",
      "进度: 8/32  error_min: 0.037006042888029 iter_num: 3999\n",
      "进度: 9/32  error_min: 0.3139060701213682 iter_num: 3999\n",
      "进度: 10/32  error_min: 0.20281119248693813 iter_num: 3999\n",
      "进度: 11/32  error_min: 0.41726655417762215 iter_num: 3999\n",
      "进度: 12/32  error_min: 0.3933947248581575 iter_num: 3999\n",
      "进度: 13/32  error_min: 0.10397192014797352 iter_num: 3999\n",
      "进度: 14/32  error_min: 0.044827821438157 iter_num: 3999\n",
      "进度: 15/32  error_min: 1.4465259981610856e-05 iter_num: 3999\n",
      "进度: 16/32  error_min: 0.027015541403967336 iter_num: 3999\n",
      "进度: 17/32  error_min: 0.23023604776614837 iter_num: 3999\n",
      "进度: 18/32  error_min: 0.055329611409609125 iter_num: 3999\n",
      "进度: 19/32  error_min: 0.33949787956526734 iter_num: 3999\n",
      "进度: 20/32  error_min: 0.43939817633099754 iter_num: 3999\n",
      "进度: 21/32  error_min: 0.01942037048804157 iter_num: 3999\n",
      "进度: 22/32  error_min: 0.0057110067124979125 iter_num: 3999\n",
      "进度: 23/32  error_min: 0.0018278502639246241 iter_num: 3999\n",
      "进度: 24/32  error_min: 0.3583400244246343 iter_num: 3999\n",
      "进度: 25/32  error_min: 0.012083057948582665 iter_num: 3999\n",
      "进度: 26/32  error_min: 0.01081059914309701 iter_num: 3999\n",
      "进度: 27/32  error_min: 0.4309266251103069 iter_num: 3999\n",
      "进度: 28/32  error_min: 0.20752670278374652 iter_num: 3999\n",
      "进度: 29/32  error_min: 0.17580388404078606 iter_num: 3999\n",
      "进度: 30/32  error_min: 0.36470694412271 iter_num: 3999\n",
      "进度: 31/32  error_min: 0.00867050059129193 iter_num: 3999\n",
      "进度: 32/32  error_min: 0.12128289218156219 iter_num: 3999\n",
      "mean of iter_num: 3999.0\n",
      "\n",
      " mean of error is： 0.18179038361815375\n",
      "\n",
      "error_min_list:\n",
      " [0.18778399892822117, 0.15605287245380872, 0.2736579900172741, 0.5503106382610887, 0.0469588441893376, 0.14476512760846094, 0.13597629865733019, 0.037006042888029, 0.3139060701213682, 0.20281119248693813, 0.41726655417762215, 0.3933947248581575, 0.10397192014797352, 0.044827821438157, 1.4465259981610856e-05, 0.027015541403967336, 0.23023604776614837, 0.055329611409609125, 0.33949787956526734, 0.43939817633099754, 0.01942037048804157, 0.0057110067124979125, 0.0018278502639246241, 0.3583400244246343, 0.012083057948582665, 0.01081059914309701, 0.4309266251103069, 0.20752670278374652, 0.17580388404078606, 0.36470694412271, 0.00867050059129193, 0.12128289218156219]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi/2\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_0('01').on(0)\n",
    "# circ += gate_0('02').on(0)\n",
    "# circ += gate_0('03').on(0)\n",
    "# circ += gate_0('04').on(0)\n",
    "# circ += gate_0('05').on(0)\n",
    "# circ += gate_0('06').on(0)\n",
    "# circ += gate_0('07').on(0)\n",
    "# circ += gate_0('08').on(0)\n",
    "# circ += gate_0('09').on(0)\n",
    "\n",
    "# circ += gate_0('10').on(0)\n",
    "# circ += gate_0('11').on(0)\n",
    "# circ += gate_0('12').on(0)\n",
    "# circ += gate_0('13').on(0)\n",
    "# circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "\n",
    "error_min_list = [] \n",
    "m_list = []\n",
    "lr = 0.05\n",
    "for i in range(len(u_mats)):\n",
    "    Quantum_net = MQLayer(grad_ops)\n",
    "    opti = Adam(Quantum_net.trainable_params(), learning_rate=lr)  \n",
    "    net = TrainOneStepCell(Quantum_net, opti)\n",
    "    error_min = 1\n",
    "    for j in range(len(train_x)):\n",
    "        net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "        params = abs(Quantum_net.weight.asnumpy())\n",
    "        final_state = []\n",
    "        for k in range(100): # 100 个测试点\n",
    "            sim.reset()\n",
    "            sim.set_qs(eval_x[k])\n",
    "            sim.apply_circuit(circ, params)\n",
    "            final_state.append(sim.get_qs())\n",
    "        error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "        error_min = min(error, error_min)\n",
    "        if error_min < 1e-5:\n",
    "            break\n",
    "    error_min_list.append(error_min)\n",
    "    m_list.append(j)\n",
    "    print(f\"进度: {i+1}/{len(u_mats)} \", 'error_min:', error_min, 'iter_num:', j)\n",
    "    \n",
    "print('mean of iter_num:', np.mean(m_list))\n",
    "print('\\n mean of error is：', np.mean(error_min_list))\n",
    "print('\\nerror_min_list:\\n', error_min_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "e8111559",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "进度: 1/32  error_min: 0.2687362796012267 iter_num: 3999\n",
      "进度: 2/32  error_min: 0.010398661602562642 iter_num: 3999\n",
      "进度: 3/32  error_min: 0.23972004295449012 iter_num: 3999\n",
      "进度: 4/32  error_min: 0.013601649184351472 iter_num: 3999\n",
      "进度: 5/32  error_min: 0.09727191125357382 iter_num: 3999\n",
      "进度: 6/32  error_min: 0.09658664757452451 iter_num: 3999\n",
      "进度: 7/32  error_min: 0.39156221217934206 iter_num: 3999\n",
      "进度: 8/32  error_min: 0.03116913861756543 iter_num: 3999\n",
      "进度: 9/32  error_min: 0.23261370870503162 iter_num: 3999\n",
      "进度: 10/32  error_min: 9.347177719054578e-06 iter_num: 3580\n",
      "进度: 11/32  error_min: 0.28320665933444433 iter_num: 3999\n",
      "进度: 12/32  error_min: 0.10417744059862333 iter_num: 3999\n",
      "进度: 13/32  error_min: 9.723921325033302e-06 iter_num: 2273\n",
      "进度: 14/32  error_min: 0.0008854730320756454 iter_num: 3999\n",
      "进度: 15/32  error_min: 0.005649610096432722 iter_num: 3999\n",
      "进度: 16/32  error_min: 0.01621255382737974 iter_num: 3999\n",
      "进度: 17/32  error_min: 0.13385245764688214 iter_num: 3999\n",
      "进度: 18/32  error_min: 9.967531425791876e-06 iter_num: 2460\n",
      "进度: 19/32  error_min: 0.15281642224041647 iter_num: 3999\n",
      "进度: 20/32  error_min: 0.2967873153635432 iter_num: 3999\n",
      "进度: 21/32  error_min: 0.028714139662043503 iter_num: 3999\n",
      "进度: 22/32  error_min: 0.04143634653620387 iter_num: 3999\n",
      "进度: 23/32  error_min: 9.250273027561207e-06 iter_num: 509\n",
      "进度: 24/32  error_min: 0.006873352658177678 iter_num: 3999\n",
      "进度: 25/32  error_min: 0.20367057520115428 iter_num: 3999\n",
      "进度: 26/32  error_min: 0.010603623655698113 iter_num: 3999\n",
      "进度: 27/32  error_min: 0.3764977347950704 iter_num: 3999\n",
      "进度: 28/32  error_min: 0.2072004553838811 iter_num: 3999\n",
      "进度: 29/32  error_min: 3.846591401179822e-06 iter_num: 3981\n",
      "进度: 30/32  error_min: 0.3732643662093702 iter_num: 3999\n",
      "进度: 31/32  error_min: 9.819523366871863e-06 iter_num: 1446\n",
      "进度: 32/32  error_min: 0.044033391496281826 iter_num: 3999\n",
      "mean of iter_num: 3694.46875\n",
      "\n",
      " mean of error is： 0.11461231638839414\n",
      "\n",
      "error_min_list:\n",
      " [0.2687362796012267, 0.010398661602562642, 0.23972004295449012, 0.013601649184351472, 0.09727191125357382, 0.09658664757452451, 0.39156221217934206, 0.03116913861756543, 0.23261370870503162, 9.347177719054578e-06, 0.28320665933444433, 0.10417744059862333, 9.723921325033302e-06, 0.0008854730320756454, 0.005649610096432722, 0.01621255382737974, 0.13385245764688214, 9.967531425791876e-06, 0.15281642224041647, 0.2967873153635432, 0.028714139662043503, 0.04143634653620387, 9.250273027561207e-06, 0.006873352658177678, 0.20367057520115428, 0.010603623655698113, 0.3764977347950704, 0.2072004553838811, 3.846591401179822e-06, 0.3732643662093702, 9.819523366871863e-06, 0.044033391496281826]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi/2\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_0('01').on(0)\n",
    "circ += gate_0('02').on(0)\n",
    "# circ += gate_0('03').on(0)\n",
    "# circ += gate_0('04').on(0)\n",
    "# circ += gate_0('05').on(0)\n",
    "# circ += gate_0('06').on(0)\n",
    "# circ += gate_0('07').on(0)\n",
    "# circ += gate_0('08').on(0)\n",
    "# circ += gate_0('09').on(0)\n",
    "\n",
    "# circ += gate_0('10').on(0)\n",
    "# circ += gate_0('11').on(0)\n",
    "# circ += gate_0('12').on(0)\n",
    "# circ += gate_0('13').on(0)\n",
    "# circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "\n",
    "error_min_list = [] \n",
    "m_list = []\n",
    "lr = 0.05\n",
    "for i in range(len(u_mats)):\n",
    "    Quantum_net = MQLayer(grad_ops)\n",
    "    opti = Adam(Quantum_net.trainable_params(), learning_rate=lr)  \n",
    "    net = TrainOneStepCell(Quantum_net, opti)\n",
    "    error_min = 1\n",
    "    for j in range(len(train_x)):\n",
    "        net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "        params = abs(Quantum_net.weight.asnumpy())\n",
    "        final_state = []\n",
    "        for k in range(100): # 100 个测试点\n",
    "            sim.reset()\n",
    "            sim.set_qs(eval_x[k])\n",
    "            sim.apply_circuit(circ, params)\n",
    "            final_state.append(sim.get_qs())\n",
    "        error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "        error_min = min(error, error_min)\n",
    "        if error_min < 1e-5:\n",
    "            break\n",
    "    error_min_list.append(error_min)\n",
    "    m_list.append(j)\n",
    "    print(f\"进度: {i+1}/{len(u_mats)} \", 'error_min:', error_min, 'iter_num:', j)\n",
    "    \n",
    "print('mean of iter_num:', np.mean(m_list))\n",
    "print('\\n mean of error is：', np.mean(error_min_list))\n",
    "print('\\nerror_min_list:\\n', error_min_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "59526481",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "进度: 1/32  error_min: 0.23436507850590937 iter_num: 3999\n",
      "进度: 2/32  error_min: 0.051828259285021105 iter_num: 3999\n",
      "进度: 3/32  error_min: 0.05116006086161329 iter_num: 3999\n",
      "进度: 4/32  error_min: 0.03195895606103483 iter_num: 3999\n",
      "进度: 5/32  error_min: 9.801835487932564e-06 iter_num: 2646\n",
      "进度: 6/32  error_min: 0.010659088344121326 iter_num: 3999\n",
      "进度: 7/32  error_min: 0.10274482981702593 iter_num: 3999\n",
      "进度: 8/32  error_min: 6.915588595224342e-06 iter_num: 1053\n",
      "进度: 9/32  error_min: 0.10127830937341564 iter_num: 3999\n",
      "进度: 10/32  error_min: 7.1330841521222155e-06 iter_num: 585\n",
      "进度: 11/32  error_min: 0.2637590922875386 iter_num: 3999\n",
      "进度: 12/32  error_min: 0.041564703664677016 iter_num: 3999\n",
      "进度: 13/32  error_min: 9.247968462355871e-06 iter_num: 1973\n",
      "进度: 14/32  error_min: 7.093253096779328e-06 iter_num: 1308\n",
      "进度: 15/32  error_min: 9.27304117903649e-06 iter_num: 455\n",
      "进度: 16/32  error_min: 0.006051383503706709 iter_num: 3999\n",
      "进度: 17/32  error_min: 8.949383219269968e-06 iter_num: 1786\n",
      "进度: 18/32  error_min: 3.814933574486368e-06 iter_num: 1902\n",
      "进度: 19/32  error_min: 0.11421365247959336 iter_num: 3999\n",
      "进度: 20/32  error_min: 0.021834619760024654 iter_num: 3999\n",
      "进度: 21/32  error_min: 0.04263174801762226 iter_num: 3999\n",
      "进度: 22/32  error_min: 9.476712980660551e-05 iter_num: 3999\n",
      "进度: 23/32  error_min: 0.00031179960724503353 iter_num: 3999\n",
      "进度: 24/32  error_min: 0.01940646410313296 iter_num: 3999\n",
      "进度: 25/32  error_min: 0.056294945841881106 iter_num: 3999\n",
      "进度: 26/32  error_min: 0.007911513103748602 iter_num: 3999\n",
      "进度: 27/32  error_min: 0.05836447004288914 iter_num: 3999\n",
      "进度: 28/32  error_min: 0.20780168139750455 iter_num: 3999\n",
      "进度: 29/32  error_min: 8.269356039147802e-06 iter_num: 1707\n",
      "进度: 30/32  error_min: 0.3522572620859503 iter_num: 3999\n",
      "进度: 31/32  error_min: 9.46574897897623e-06 iter_num: 512\n",
      "进度: 32/32  error_min: 0.013404158694868107 iter_num: 3999\n",
      "mean of iter_num: 3184.53125\n",
      "\n",
      " mean of error is： 0.05593677525503487\n",
      "\n",
      "error_min_list:\n",
      " [0.23436507850590937, 0.051828259285021105, 0.05116006086161329, 0.03195895606103483, 9.801835487932564e-06, 0.010659088344121326, 0.10274482981702593, 6.915588595224342e-06, 0.10127830937341564, 7.1330841521222155e-06, 0.2637590922875386, 0.041564703664677016, 9.247968462355871e-06, 7.093253096779328e-06, 9.27304117903649e-06, 0.006051383503706709, 8.949383219269968e-06, 3.814933574486368e-06, 0.11421365247959336, 0.021834619760024654, 0.04263174801762226, 9.476712980660551e-05, 0.00031179960724503353, 0.01940646410313296, 0.056294945841881106, 0.007911513103748602, 0.05836447004288914, 0.20780168139750455, 8.269356039147802e-06, 0.3522572620859503, 9.46574897897623e-06, 0.013404158694868107]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi/2\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_0('01').on(0)\n",
    "circ += gate_0('02').on(0)\n",
    "circ += gate_0('03').on(0)\n",
    "# circ += gate_0('04').on(0)\n",
    "# circ += gate_0('05').on(0)\n",
    "# circ += gate_0('06').on(0)\n",
    "# circ += gate_0('07').on(0)\n",
    "# circ += gate_0('08').on(0)\n",
    "# circ += gate_0('09').on(0)\n",
    "\n",
    "# circ += gate_0('10').on(0)\n",
    "# circ += gate_0('11').on(0)\n",
    "# circ += gate_0('12').on(0)\n",
    "# circ += gate_0('13').on(0)\n",
    "# circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "\n",
    "error_min_list = [] \n",
    "m_list = []\n",
    "lr = 0.05\n",
    "for i in range(len(u_mats)):\n",
    "    Quantum_net = MQLayer(grad_ops)\n",
    "    opti = Adam(Quantum_net.trainable_params(), learning_rate=lr)  \n",
    "    net = TrainOneStepCell(Quantum_net, opti)\n",
    "    error_min = 1\n",
    "    for j in range(len(train_x)):\n",
    "        net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "        params = abs(Quantum_net.weight.asnumpy())\n",
    "        final_state = []\n",
    "        for k in range(100): # 100 个测试点\n",
    "            sim.reset()\n",
    "            sim.set_qs(eval_x[k])\n",
    "            sim.apply_circuit(circ, params)\n",
    "            final_state.append(sim.get_qs())\n",
    "        error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "        error_min = min(error, error_min)\n",
    "        if error_min < 1e-5:\n",
    "            break\n",
    "    error_min_list.append(error_min)\n",
    "    m_list.append(j)\n",
    "    print(f\"进度: {i+1}/{len(u_mats)} \", 'error_min:', error_min, 'iter_num:', j)\n",
    "    \n",
    "print('mean of iter_num:', np.mean(m_list))\n",
    "print('\\n mean of error is：', np.mean(error_min_list))\n",
    "print('\\nerror_min_list:\\n', error_min_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "a9fd493f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "进度: 1/32  error_min: 8.764936255789557e-06 iter_num: 349\n",
      "进度: 2/32  error_min: 8.68173799262184e-06 iter_num: 3488\n",
      "进度: 3/32  error_min: 9.705969495565903e-06 iter_num: 600\n",
      "进度: 4/32  error_min: 0.030599604828755678 iter_num: 3999\n",
      "进度: 5/32  error_min: 2.2866162391110834e-05 iter_num: 3999\n",
      "进度: 6/32  error_min: 5.907934756299582e-06 iter_num: 970\n",
      "进度: 7/32  error_min: 0.08328405180081233 iter_num: 3999\n",
      "进度: 8/32  error_min: 9.293576025859451e-06 iter_num: 1753\n",
      "进度: 9/32  error_min: 0.00018011514149873786 iter_num: 3999\n",
      "进度: 10/32  error_min: 3.654639651795577e-06 iter_num: 355\n",
      "进度: 11/32  error_min: 0.03586565913629336 iter_num: 3999\n",
      "进度: 12/32  error_min: 8.979772590400614e-06 iter_num: 3513\n",
      "进度: 13/32  error_min: 9.67012178487714e-06 iter_num: 731\n",
      "进度: 14/32  error_min: 1.9607755619599487e-05 iter_num: 3999\n",
      "进度: 15/32  error_min: 8.450028221917982e-06 iter_num: 773\n",
      "进度: 16/32  error_min: 0.00678369144508828 iter_num: 3999\n",
      "进度: 17/32  error_min: 5.758011676459951e-06 iter_num: 1195\n",
      "进度: 18/32  error_min: 9.955665252192603e-06 iter_num: 1481\n",
      "进度: 19/32  error_min: 0.012541117199241336 iter_num: 3999\n",
      "进度: 20/32  error_min: 0.010171488627100711 iter_num: 3999\n",
      "进度: 21/32  error_min: 9.48669750133746e-06 iter_num: 2959\n",
      "进度: 22/32  error_min: 8.841128399716958e-06 iter_num: 2401\n",
      "进度: 23/32  error_min: 0.001696574757017899 iter_num: 3999\n",
      "进度: 24/32  error_min: 0.009275230093401254 iter_num: 3999\n",
      "进度: 25/32  error_min: 0.0024907607128549225 iter_num: 3999\n",
      "进度: 26/32  error_min: 0.0017942822231404865 iter_num: 3999\n",
      "进度: 27/32  error_min: 0.03473853378163927 iter_num: 3999\n",
      "进度: 28/32  error_min: 0.0006153965035717857 iter_num: 3999\n",
      "进度: 29/32  error_min: 8.539606995872084e-06 iter_num: 403\n",
      "进度: 30/32  error_min: 0.1848288498812547 iter_num: 3999\n",
      "进度: 31/32  error_min: 8.650868440707171e-06 iter_num: 776\n",
      "进度: 32/32  error_min: 0.0047886006267677805 iter_num: 3999\n",
      "mean of iter_num: 2804.0625\n",
      "\n",
      " mean of error is： 0.013119399105359083\n",
      "\n",
      "error_min_list:\n",
      " [8.764936255789557e-06, 8.68173799262184e-06, 9.705969495565903e-06, 0.030599604828755678, 2.2866162391110834e-05, 5.907934756299582e-06, 0.08328405180081233, 9.293576025859451e-06, 0.00018011514149873786, 3.654639651795577e-06, 0.03586565913629336, 8.979772590400614e-06, 9.67012178487714e-06, 1.9607755619599487e-05, 8.450028221917982e-06, 0.00678369144508828, 5.758011676459951e-06, 9.955665252192603e-06, 0.012541117199241336, 0.010171488627100711, 9.48669750133746e-06, 8.841128399716958e-06, 0.001696574757017899, 0.009275230093401254, 0.0024907607128549225, 0.0017942822231404865, 0.03473853378163927, 0.0006153965035717857, 8.539606995872084e-06, 0.1848288498812547, 8.650868440707171e-06, 0.0047886006267677805]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi/2\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_0('01').on(0)\n",
    "circ += gate_0('02').on(0)\n",
    "circ += gate_0('03').on(0)\n",
    "circ += gate_0('04').on(0)\n",
    "# circ += gate_0('05').on(0)\n",
    "# circ += gate_0('06').on(0)\n",
    "# circ += gate_0('07').on(0)\n",
    "# circ += gate_0('08').on(0)\n",
    "# circ += gate_0('09').on(0)\n",
    "\n",
    "# circ += gate_0('10').on(0)\n",
    "# circ += gate_0('11').on(0)\n",
    "# circ += gate_0('12').on(0)\n",
    "# circ += gate_0('13').on(0)\n",
    "# circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "\n",
    "error_min_list = [] \n",
    "m_list = []\n",
    "lr = 0.05\n",
    "for i in range(len(u_mats)):\n",
    "    Quantum_net = MQLayer(grad_ops)\n",
    "    opti = Adam(Quantum_net.trainable_params(), learning_rate=lr)  \n",
    "    net = TrainOneStepCell(Quantum_net, opti)\n",
    "    error_min = 1\n",
    "    for j in range(len(train_x)):\n",
    "        net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "        params = abs(Quantum_net.weight.asnumpy())\n",
    "        final_state = []\n",
    "        for k in range(100): # 100 个测试点\n",
    "            sim.reset()\n",
    "            sim.set_qs(eval_x[k])\n",
    "            sim.apply_circuit(circ, params)\n",
    "            final_state.append(sim.get_qs())\n",
    "        error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "        error_min = min(error, error_min)\n",
    "        if error_min < 1e-5:\n",
    "            break\n",
    "    error_min_list.append(error_min)\n",
    "    m_list.append(j)\n",
    "    print(f\"进度: {i+1}/{len(u_mats)} \", 'error_min:', error_min, 'iter_num:', j)\n",
    "    \n",
    "print('mean of iter_num:', np.mean(m_list))\n",
    "print('\\n mean of error is：', np.mean(error_min_list))\n",
    "print('\\nerror_min_list:\\n', error_min_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "3efc12f6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "进度: 1/32  error_min: 8.548877371783448e-06 iter_num: 2115\n",
      "进度: 2/32  error_min: 9.577031847118889e-06 iter_num: 2089\n",
      "进度: 3/32  error_min: 9.82120537118547e-06 iter_num: 285\n",
      "进度: 4/32  error_min: 0.009429408909622738 iter_num: 3999\n",
      "进度: 5/32  error_min: 9.450679860578681e-06 iter_num: 1388\n",
      "进度: 6/32  error_min: 8.68603677617319e-06 iter_num: 2174\n",
      "进度: 7/32  error_min: 5.022051779768333e-06 iter_num: 485\n",
      "进度: 8/32  error_min: 9.910529427337167e-06 iter_num: 3420\n",
      "进度: 9/32  error_min: 0.00249722526260443 iter_num: 3999\n",
      "进度: 10/32  error_min: 9.120734732248614e-06 iter_num: 484\n",
      "进度: 11/32  error_min: 0.07550152165487056 iter_num: 3999\n",
      "进度: 12/32  error_min: 2.4677548797757964e-06 iter_num: 2919\n",
      "进度: 13/32  error_min: 9.201035537698132e-06 iter_num: 718\n",
      "进度: 14/32  error_min: 6.855918965431584e-06 iter_num: 314\n",
      "进度: 15/32  error_min: 9.214719092653922e-06 iter_num: 901\n",
      "进度: 16/32  error_min: 6.733023525273829e-06 iter_num: 1691\n",
      "进度: 17/32  error_min: 8.913809145250084e-06 iter_num: 1890\n",
      "进度: 18/32  error_min: 5.929816606631277e-06 iter_num: 222\n",
      "进度: 19/32  error_min: 0.00013845067593243332 iter_num: 3999\n",
      "进度: 20/32  error_min: 3.1674075139376257e-06 iter_num: 3599\n",
      "进度: 21/32  error_min: 0.0005096003574092123 iter_num: 3999\n",
      "进度: 22/32  error_min: 5.487924790714693e-06 iter_num: 1062\n",
      "进度: 23/32  error_min: 8.855862758561095e-06 iter_num: 702\n",
      "进度: 24/32  error_min: 8.28349385839644e-06 iter_num: 3761\n",
      "进度: 25/32  error_min: 8.03766315504717e-06 iter_num: 953\n",
      "进度: 26/32  error_min: 8.68207619586503e-06 iter_num: 1370\n",
      "进度: 27/32  error_min: 0.013531245866906794 iter_num: 3999\n",
      "进度: 28/32  error_min: 9.812909115725077e-06 iter_num: 3106\n",
      "进度: 29/32  error_min: 7.694383107659242e-06 iter_num: 384\n",
      "进度: 30/32  error_min: 0.000130611130684688 iter_num: 3999\n",
      "进度: 31/32  error_min: 9.31422890093625e-06 iter_num: 624\n",
      "进度: 32/32  error_min: 1.921293048989803e-06 iter_num: 2397\n",
      "mean of iter_num: 2095.1875\n",
      "\n",
      " mean of error is： 0.0031852741976686125\n",
      "\n",
      "error_min_list:\n",
      " [8.548877371783448e-06, 9.577031847118889e-06, 9.82120537118547e-06, 0.009429408909622738, 9.450679860578681e-06, 8.68603677617319e-06, 5.022051779768333e-06, 9.910529427337167e-06, 0.00249722526260443, 9.120734732248614e-06, 0.07550152165487056, 2.4677548797757964e-06, 9.201035537698132e-06, 6.855918965431584e-06, 9.214719092653922e-06, 6.733023525273829e-06, 8.913809145250084e-06, 5.929816606631277e-06, 0.00013845067593243332, 3.1674075139376257e-06, 0.0005096003574092123, 5.487924790714693e-06, 8.855862758561095e-06, 8.28349385839644e-06, 8.03766315504717e-06, 8.68207619586503e-06, 0.013531245866906794, 9.812909115725077e-06, 7.694383107659242e-06, 0.000130611130684688, 9.31422890093625e-06, 1.921293048989803e-06]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi/2\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_0('01').on(0)\n",
    "circ += gate_0('02').on(0)\n",
    "circ += gate_0('03').on(0)\n",
    "circ += gate_0('04').on(0)\n",
    "circ += gate_0('05').on(0)\n",
    "# circ += gate_0('06').on(0)\n",
    "# circ += gate_0('07').on(0)\n",
    "# circ += gate_0('08').on(0)\n",
    "# circ += gate_0('09').on(0)\n",
    "\n",
    "# circ += gate_0('10').on(0)\n",
    "# circ += gate_0('11').on(0)\n",
    "# circ += gate_0('12').on(0)\n",
    "# circ += gate_0('13').on(0)\n",
    "# circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "\n",
    "error_min_list = [] \n",
    "m_list = []\n",
    "lr = 0.05\n",
    "for i in range(len(u_mats)):\n",
    "    Quantum_net = MQLayer(grad_ops)\n",
    "    opti = Adam(Quantum_net.trainable_params(), learning_rate=lr)  \n",
    "    net = TrainOneStepCell(Quantum_net, opti)\n",
    "    error_min = 1\n",
    "    for j in range(len(train_x)):\n",
    "        net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "        params = abs(Quantum_net.weight.asnumpy())\n",
    "        final_state = []\n",
    "        for k in range(100): # 100 个测试点\n",
    "            sim.reset()\n",
    "            sim.set_qs(eval_x[k])\n",
    "            sim.apply_circuit(circ, params)\n",
    "            final_state.append(sim.get_qs())\n",
    "        error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "        error_min = min(error, error_min)\n",
    "        if error_min < 1e-5:\n",
    "            break\n",
    "    error_min_list.append(error_min)\n",
    "    m_list.append(j)\n",
    "    print(f\"进度: {i+1}/{len(u_mats)} \", 'error_min:', error_min, 'iter_num:', j)\n",
    "    \n",
    "print('mean of iter_num:', np.mean(m_list))\n",
    "print('\\n mean of error is：', np.mean(error_min_list))\n",
    "print('\\nerror_min_list:\\n', error_min_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "e7cd522c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "进度: 1/32  error_min: 6.118761978979315e-06 iter_num: 335\n",
      "进度: 2/32  error_min: 8.234375922122616e-06 iter_num: 1864\n",
      "进度: 3/32  error_min: 8.720360216041279e-06 iter_num: 2529\n",
      "进度: 4/32  error_min: 0.018545381783878434 iter_num: 3999\n",
      "进度: 5/32  error_min: 6.967917017597358e-06 iter_num: 1738\n",
      "进度: 6/32  error_min: 9.955042843623474e-06 iter_num: 2151\n",
      "进度: 7/32  error_min: 8.864843651479326e-06 iter_num: 506\n",
      "进度: 8/32  error_min: 3.7443956298899295e-06 iter_num: 2947\n",
      "进度: 9/32  error_min: 8.424956932873151e-06 iter_num: 1161\n",
      "进度: 10/32  error_min: 1.5599887684958347e-06 iter_num: 521\n",
      "进度: 11/32  error_min: 0.007955083828605436 iter_num: 3999\n",
      "进度: 12/32  error_min: 0.001938082983555911 iter_num: 3999\n",
      "进度: 13/32  error_min: 8.55379760456021e-06 iter_num: 313\n",
      "进度: 14/32  error_min: 9.581085096743713e-06 iter_num: 1420\n",
      "进度: 15/32  error_min: 9.294505045498447e-06 iter_num: 332\n",
      "进度: 16/32  error_min: 6.180323825044631e-06 iter_num: 1020\n",
      "进度: 17/32  error_min: 6.5557211746947175e-06 iter_num: 539\n",
      "进度: 18/32  error_min: 7.056651173953377e-06 iter_num: 434\n",
      "进度: 19/32  error_min: 0.15576406910587115 iter_num: 3999\n",
      "进度: 20/32  error_min: 8.645495983672369e-06 iter_num: 547\n",
      "进度: 21/32  error_min: 0.005452897346737706 iter_num: 3999\n",
      "进度: 22/32  error_min: 6.876278596190666e-06 iter_num: 552\n",
      "进度: 23/32  error_min: 4.741378863637458e-06 iter_num: 853\n",
      "进度: 24/32  error_min: 8.31792326760894e-06 iter_num: 1988\n",
      "进度: 25/32  error_min: 9.86173333838991e-06 iter_num: 1403\n",
      "进度: 26/32  error_min: 7.454144965723941e-06 iter_num: 948\n",
      "进度: 27/32  error_min: 0.00024089759665613109 iter_num: 3999\n",
      "进度: 28/32  error_min: 9.45861563295125e-07 iter_num: 1887\n",
      "进度: 29/32  error_min: 9.993264873608965e-06 iter_num: 293\n",
      "进度: 30/32  error_min: 7.318151149182661e-06 iter_num: 1298\n",
      "进度: 31/32  error_min: 7.150298997116167e-06 iter_num: 690\n",
      "进度: 32/32  error_min: 9.80810613571137e-06 iter_num: 1731\n",
      "mean of iter_num: 1687.3125\n",
      "\n",
      " mean of error is： 0.005940229312810016\n",
      "\n",
      "error_min_list:\n",
      " [6.118761978979315e-06, 8.234375922122616e-06, 8.720360216041279e-06, 0.018545381783878434, 6.967917017597358e-06, 9.955042843623474e-06, 8.864843651479326e-06, 3.7443956298899295e-06, 8.424956932873151e-06, 1.5599887684958347e-06, 0.007955083828605436, 0.001938082983555911, 8.55379760456021e-06, 9.581085096743713e-06, 9.294505045498447e-06, 6.180323825044631e-06, 6.5557211746947175e-06, 7.056651173953377e-06, 0.15576406910587115, 8.645495983672369e-06, 0.005452897346737706, 6.876278596190666e-06, 4.741378863637458e-06, 8.31792326760894e-06, 9.86173333838991e-06, 7.454144965723941e-06, 0.00024089759665613109, 9.45861563295125e-07, 9.993264873608965e-06, 7.318151149182661e-06, 7.150298997116167e-06, 9.80810613571137e-06]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi/2\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_0('01').on(0)\n",
    "circ += gate_0('02').on(0)\n",
    "circ += gate_0('03').on(0)\n",
    "circ += gate_0('04').on(0)\n",
    "circ += gate_0('05').on(0)\n",
    "circ += gate_0('06').on(0)\n",
    "# circ += gate_0('07').on(0)\n",
    "# circ += gate_0('08').on(0)\n",
    "# circ += gate_0('09').on(0)\n",
    "\n",
    "# circ += gate_0('10').on(0)\n",
    "# circ += gate_0('11').on(0)\n",
    "# circ += gate_0('12').on(0)\n",
    "# circ += gate_0('13').on(0)\n",
    "# circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "\n",
    "error_min_list = [] \n",
    "m_list = []\n",
    "lr = 0.05\n",
    "for i in range(len(u_mats)):\n",
    "    Quantum_net = MQLayer(grad_ops)\n",
    "    opti = Adam(Quantum_net.trainable_params(), learning_rate=lr)  \n",
    "    net = TrainOneStepCell(Quantum_net, opti)\n",
    "    error_min = 1\n",
    "    for j in range(len(train_x)):\n",
    "        net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "        params = abs(Quantum_net.weight.asnumpy())\n",
    "        final_state = []\n",
    "        for k in range(100): # 100 个测试点\n",
    "            sim.reset()\n",
    "            sim.set_qs(eval_x[k])\n",
    "            sim.apply_circuit(circ, params)\n",
    "            final_state.append(sim.get_qs())\n",
    "        error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "        error_min = min(error, error_min)\n",
    "        if error_min < 1e-5:\n",
    "            break\n",
    "    error_min_list.append(error_min)\n",
    "    m_list.append(j)\n",
    "    print(f\"进度: {i+1}/{len(u_mats)} \", 'error_min:', error_min, 'iter_num:', j)\n",
    "    \n",
    "print('mean of iter_num:', np.mean(m_list))\n",
    "print('\\n mean of error is：', np.mean(error_min_list))\n",
    "print('\\nerror_min_list:\\n', error_min_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "75fb2d30",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "进度: 1/32  error_min: 2.906626915155641e-06 iter_num: 2412\n",
      "进度: 2/32  error_min: 7.268805465754369e-06 iter_num: 1378\n",
      "进度: 3/32  error_min: 9.609328356141589e-06 iter_num: 729\n",
      "进度: 4/32  error_min: 4.347346867272783e-06 iter_num: 3617\n",
      "进度: 5/32  error_min: 5.372868715602941e-06 iter_num: 535\n",
      "进度: 6/32  error_min: 9.475299826311456e-06 iter_num: 1892\n",
      "进度: 7/32  error_min: 9.635064586954734e-06 iter_num: 302\n",
      "进度: 8/32  error_min: 8.738703307753504e-06 iter_num: 276\n",
      "进度: 9/32  error_min: 9.23702258637249e-06 iter_num: 2573\n",
      "进度: 10/32  error_min: 9.096738704972296e-06 iter_num: 320\n",
      "进度: 11/32  error_min: 0.032770047316698525 iter_num: 3999\n",
      "进度: 12/32  error_min: 4.8776644105963385e-06 iter_num: 1062\n",
      "进度: 13/32  error_min: 9.747907629198416e-06 iter_num: 427\n",
      "进度: 14/32  error_min: 8.36114599322979e-06 iter_num: 953\n",
      "进度: 15/32  error_min: 9.748525600206115e-06 iter_num: 369\n",
      "进度: 16/32  error_min: 7.894019974807875e-06 iter_num: 1052\n",
      "进度: 17/32  error_min: 7.653891384795664e-06 iter_num: 466\n",
      "进度: 18/32  error_min: 8.653690417581572e-06 iter_num: 304\n",
      "进度: 19/32  error_min: 5.688838705664168e-06 iter_num: 466\n",
      "进度: 20/32  error_min: 5.432468877519803e-06 iter_num: 3345\n",
      "进度: 21/32  error_min: 8.042326293256075e-06 iter_num: 207\n",
      "进度: 22/32  error_min: 9.411718849938744e-06 iter_num: 714\n",
      "进度: 23/32  error_min: 0.005667177599366746 iter_num: 3999\n",
      "进度: 24/32  error_min: 7.784553744394351e-06 iter_num: 771\n",
      "进度: 25/32  error_min: 5.268520803070054e-06 iter_num: 1901\n",
      "进度: 26/32  error_min: 8.44447640535595e-06 iter_num: 1595\n",
      "进度: 27/32  error_min: 6.898859482462605e-06 iter_num: 754\n",
      "进度: 28/32  error_min: 0.013289935664775765 iter_num: 3999\n",
      "进度: 29/32  error_min: 3.834574143768421e-06 iter_num: 387\n",
      "进度: 30/32  error_min: 9.12058031188323e-06 iter_num: 782\n",
      "进度: 31/32  error_min: 1.9488032874104277e-06 iter_num: 536\n",
      "进度: 32/32  error_min: 8.842041970602565e-06 iter_num: 2772\n",
      "mean of iter_num: 1402.9375\n",
      "\n",
      " mean of error is： 0.001623140718576846\n",
      "\n",
      "error_min_list:\n",
      " [2.906626915155641e-06, 7.268805465754369e-06, 9.609328356141589e-06, 4.347346867272783e-06, 5.372868715602941e-06, 9.475299826311456e-06, 9.635064586954734e-06, 8.738703307753504e-06, 9.23702258637249e-06, 9.096738704972296e-06, 0.032770047316698525, 4.8776644105963385e-06, 9.747907629198416e-06, 8.36114599322979e-06, 9.748525600206115e-06, 7.894019974807875e-06, 7.653891384795664e-06, 8.653690417581572e-06, 5.688838705664168e-06, 5.432468877519803e-06, 8.042326293256075e-06, 9.411718849938744e-06, 0.005667177599366746, 7.784553744394351e-06, 5.268520803070054e-06, 8.44447640535595e-06, 6.898859482462605e-06, 0.013289935664775765, 3.834574143768421e-06, 9.12058031188323e-06, 1.9488032874104277e-06, 8.842041970602565e-06]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi/2\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_0('01').on(0)\n",
    "circ += gate_0('02').on(0)\n",
    "circ += gate_0('03').on(0)\n",
    "circ += gate_0('04').on(0)\n",
    "circ += gate_0('05').on(0)\n",
    "circ += gate_0('06').on(0)\n",
    "circ += gate_0('07').on(0)\n",
    "# circ += gate_0('08').on(0)\n",
    "# circ += gate_0('09').on(0)\n",
    "\n",
    "# circ += gate_0('10').on(0)\n",
    "# circ += gate_0('11').on(0)\n",
    "# circ += gate_0('12').on(0)\n",
    "# circ += gate_0('13').on(0)\n",
    "# circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "\n",
    "error_min_list = [] \n",
    "m_list = []\n",
    "lr = 0.05\n",
    "for i in range(len(u_mats)):\n",
    "    Quantum_net = MQLayer(grad_ops)\n",
    "    opti = Adam(Quantum_net.trainable_params(), learning_rate=lr)  \n",
    "    net = TrainOneStepCell(Quantum_net, opti)\n",
    "    error_min = 1\n",
    "    for j in range(len(train_x)):\n",
    "        net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "        params = abs(Quantum_net.weight.asnumpy())\n",
    "        final_state = []\n",
    "        for k in range(100): # 100 个测试点\n",
    "            sim.reset()\n",
    "            sim.set_qs(eval_x[k])\n",
    "            sim.apply_circuit(circ, params)\n",
    "            final_state.append(sim.get_qs())\n",
    "        error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "        error_min = min(error, error_min)\n",
    "        if error_min < 1e-5:\n",
    "            break\n",
    "    error_min_list.append(error_min)\n",
    "    m_list.append(j)\n",
    "    print(f\"进度: {i+1}/{len(u_mats)} \", 'error_min:', error_min, 'iter_num:', j)\n",
    "    \n",
    "print('mean of iter_num:', np.mean(m_list))\n",
    "print('\\n mean of error is：', np.mean(error_min_list))\n",
    "print('\\nerror_min_list:\\n', error_min_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "70cfcf33",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "进度: 1/32  error_min: 8.624528129330677e-06 iter_num: 549\n",
      "进度: 2/32  error_min: 6.1987380224337585e-06 iter_num: 1260\n",
      "进度: 3/32  error_min: 9.146348280530958e-06 iter_num: 1298\n",
      "进度: 4/32  error_min: 1.6565955861524984e-06 iter_num: 594\n",
      "进度: 5/32  error_min: 9.458303201537177e-06 iter_num: 466\n",
      "进度: 6/32  error_min: 6.6519643422413566e-06 iter_num: 799\n",
      "进度: 7/32  error_min: 8.748668846814134e-06 iter_num: 879\n",
      "进度: 8/32  error_min: 7.647590315906783e-06 iter_num: 766\n",
      "进度: 9/32  error_min: 7.778569532157498e-06 iter_num: 172\n",
      "进度: 10/32  error_min: 8.417947746419685e-06 iter_num: 1073\n",
      "进度: 11/32  error_min: 0.0005671191161752409 iter_num: 3999\n",
      "进度: 12/32  error_min: 7.812141058827216e-06 iter_num: 1128\n",
      "进度: 13/32  error_min: 9.679926145755857e-06 iter_num: 741\n",
      "进度: 14/32  error_min: 3.1021892755722646e-06 iter_num: 2196\n",
      "进度: 15/32  error_min: 9.439310558412295e-06 iter_num: 326\n",
      "进度: 16/32  error_min: 8.178728588381645e-06 iter_num: 1100\n",
      "进度: 17/32  error_min: 8.874706581729619e-06 iter_num: 310\n",
      "进度: 18/32  error_min: 5.338071778715481e-06 iter_num: 635\n",
      "进度: 19/32  error_min: 0.006031164477360851 iter_num: 3999\n",
      "进度: 20/32  error_min: 1.0470070168078216e-05 iter_num: 3999\n",
      "进度: 21/32  error_min: 5.575230219490024e-06 iter_num: 341\n",
      "进度: 22/32  error_min: 9.133453264587033e-06 iter_num: 738\n",
      "进度: 23/32  error_min: 3.131234059705612e-06 iter_num: 1390\n",
      "进度: 24/32  error_min: 6.514003533797386e-06 iter_num: 771\n",
      "进度: 25/32  error_min: 8.570553704401185e-06 iter_num: 409\n",
      "进度: 26/32  error_min: 2.309550977463992e-06 iter_num: 276\n",
      "进度: 27/32  error_min: 7.593996163235417e-06 iter_num: 430\n",
      "进度: 28/32  error_min: 5.1592428743640895e-06 iter_num: 1216\n",
      "进度: 29/32  error_min: 2.8165425429715896e-06 iter_num: 730\n",
      "进度: 30/32  error_min: 8.873468619219338e-06 iter_num: 1281\n",
      "进度: 31/32  error_min: 8.904935572484618e-06 iter_num: 1081\n",
      "进度: 32/32  error_min: 5.783398181913313e-06 iter_num: 1738\n",
      "mean of iter_num: 1146.5625\n",
      "\n",
      " mean of error is： 0.00021280855004402258\n",
      "\n",
      "error_min_list:\n",
      " [8.624528129330677e-06, 6.1987380224337585e-06, 9.146348280530958e-06, 1.6565955861524984e-06, 9.458303201537177e-06, 6.6519643422413566e-06, 8.748668846814134e-06, 7.647590315906783e-06, 7.778569532157498e-06, 8.417947746419685e-06, 0.0005671191161752409, 7.812141058827216e-06, 9.679926145755857e-06, 3.1021892755722646e-06, 9.439310558412295e-06, 8.178728588381645e-06, 8.874706581729619e-06, 5.338071778715481e-06, 0.006031164477360851, 1.0470070168078216e-05, 5.575230219490024e-06, 9.133453264587033e-06, 3.131234059705612e-06, 6.514003533797386e-06, 8.570553704401185e-06, 2.309550977463992e-06, 7.593996163235417e-06, 5.1592428743640895e-06, 2.8165425429715896e-06, 8.873468619219338e-06, 8.904935572484618e-06, 5.783398181913313e-06]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi/2\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_0('01').on(0)\n",
    "circ += gate_0('02').on(0)\n",
    "circ += gate_0('03').on(0)\n",
    "circ += gate_0('04').on(0)\n",
    "circ += gate_0('05').on(0)\n",
    "circ += gate_0('06').on(0)\n",
    "circ += gate_0('07').on(0)\n",
    "circ += gate_0('08').on(0)\n",
    "# circ += gate_0('09').on(0)\n",
    "\n",
    "# circ += gate_0('10').on(0)\n",
    "# circ += gate_0('11').on(0)\n",
    "# circ += gate_0('12').on(0)\n",
    "# circ += gate_0('13').on(0)\n",
    "# circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "\n",
    "error_min_list = [] \n",
    "m_list = []\n",
    "lr = 0.05\n",
    "for i in range(len(u_mats)):\n",
    "    Quantum_net = MQLayer(grad_ops)\n",
    "    opti = Adam(Quantum_net.trainable_params(), learning_rate=lr)  \n",
    "    net = TrainOneStepCell(Quantum_net, opti)\n",
    "    error_min = 1\n",
    "    for j in range(len(train_x)):\n",
    "        net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "        params = abs(Quantum_net.weight.asnumpy())\n",
    "        final_state = []\n",
    "        for k in range(100): # 100 个测试点\n",
    "            sim.reset()\n",
    "            sim.set_qs(eval_x[k])\n",
    "            sim.apply_circuit(circ, params)\n",
    "            final_state.append(sim.get_qs())\n",
    "        error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "        error_min = min(error, error_min)\n",
    "        if error_min < 1e-5:\n",
    "            break\n",
    "    error_min_list.append(error_min)\n",
    "    m_list.append(j)\n",
    "    print(f\"进度: {i+1}/{len(u_mats)} \", 'error_min:', error_min, 'iter_num:', j)\n",
    "    \n",
    "print('mean of iter_num:', np.mean(m_list))\n",
    "print('\\n mean of error is：', np.mean(error_min_list))\n",
    "print('\\nerror_min_list:\\n', error_min_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "27924863",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "进度: 1/32  error_min: 5.156942767814421e-06 iter_num: 283\n",
      "进度: 2/32  error_min: 9.591723020063725e-06 iter_num: 752\n",
      "进度: 3/32  error_min: 6.1277449416863305e-06 iter_num: 359\n",
      "进度: 4/32  error_min: 4.706906689855295e-06 iter_num: 1912\n",
      "进度: 5/32  error_min: 7.984503160529677e-06 iter_num: 944\n",
      "进度: 6/32  error_min: 6.658619882138339e-06 iter_num: 3376\n",
      "进度: 7/32  error_min: 9.835333197316665e-06 iter_num: 712\n",
      "进度: 8/32  error_min: 9.365616177259284e-06 iter_num: 241\n",
      "进度: 9/32  error_min: 8.530737460321625e-06 iter_num: 537\n",
      "进度: 10/32  error_min: 7.393486258111537e-06 iter_num: 758\n",
      "进度: 11/32  error_min: 9.260007145184268e-06 iter_num: 733\n",
      "进度: 12/32  error_min: 5.001205450438917e-06 iter_num: 2737\n",
      "进度: 13/32  error_min: 8.296906001348248e-06 iter_num: 447\n",
      "进度: 14/32  error_min: 5.583355962568426e-06 iter_num: 322\n",
      "进度: 15/32  error_min: 4.821026057255651e-06 iter_num: 418\n",
      "进度: 16/32  error_min: 2.120018315454608e-06 iter_num: 1065\n",
      "进度: 17/32  error_min: 7.165178131152139e-06 iter_num: 262\n",
      "进度: 18/32  error_min: 6.857629953782585e-06 iter_num: 432\n",
      "进度: 19/32  error_min: 9.602450091517056e-06 iter_num: 907\n",
      "进度: 20/32  error_min: 8.410399181313366e-06 iter_num: 1107\n",
      "进度: 21/32  error_min: 6.1321052742258075e-06 iter_num: 996\n",
      "进度: 22/32  error_min: 5.194048985246447e-06 iter_num: 2101\n",
      "进度: 23/32  error_min: 9.141462038342318e-06 iter_num: 490\n",
      "进度: 24/32  error_min: 8.854438582228674e-06 iter_num: 1377\n",
      "进度: 25/32  error_min: 8.09365617560065e-06 iter_num: 679\n",
      "进度: 26/32  error_min: 2.8874763081665478e-06 iter_num: 441\n",
      "进度: 27/32  error_min: 9.520053606992818e-06 iter_num: 3513\n",
      "进度: 28/32  error_min: 9.308379131156563e-06 iter_num: 511\n",
      "进度: 29/32  error_min: 3.726623118760486e-06 iter_num: 531\n",
      "进度: 30/32  error_min: 9.121680725310277e-06 iter_num: 1103\n",
      "进度: 31/32  error_min: 7.0717723437141444e-06 iter_num: 454\n",
      "进度: 32/32  error_min: 2.306678144825547e-06 iter_num: 236\n",
      "mean of iter_num: 960.5\n",
      "\n",
      " mean of error is： 6.994630133740076e-06\n",
      "\n",
      "error_min_list:\n",
      " [5.156942767814421e-06, 9.591723020063725e-06, 6.1277449416863305e-06, 4.706906689855295e-06, 7.984503160529677e-06, 6.658619882138339e-06, 9.835333197316665e-06, 9.365616177259284e-06, 8.530737460321625e-06, 7.393486258111537e-06, 9.260007145184268e-06, 5.001205450438917e-06, 8.296906001348248e-06, 5.583355962568426e-06, 4.821026057255651e-06, 2.120018315454608e-06, 7.165178131152139e-06, 6.857629953782585e-06, 9.602450091517056e-06, 8.410399181313366e-06, 6.1321052742258075e-06, 5.194048985246447e-06, 9.141462038342318e-06, 8.854438582228674e-06, 8.09365617560065e-06, 2.8874763081665478e-06, 9.520053606992818e-06, 9.308379131156563e-06, 3.726623118760486e-06, 9.121680725310277e-06, 7.0717723437141444e-06, 2.306678144825547e-06]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi/2\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_0('01').on(0)\n",
    "circ += gate_0('02').on(0)\n",
    "circ += gate_0('03').on(0)\n",
    "circ += gate_0('04').on(0)\n",
    "circ += gate_0('05').on(0)\n",
    "circ += gate_0('06').on(0)\n",
    "circ += gate_0('07').on(0)\n",
    "circ += gate_0('08').on(0)\n",
    "circ += gate_0('09').on(0)\n",
    "\n",
    "# circ += gate_0('10').on(0)\n",
    "# circ += gate_0('11').on(0)\n",
    "# circ += gate_0('12').on(0)\n",
    "# circ += gate_0('13').on(0)\n",
    "# circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "\n",
    "error_min_list = [] \n",
    "m_list = []\n",
    "lr = 0.05\n",
    "for i in range(len(u_mats)):\n",
    "    Quantum_net = MQLayer(grad_ops)\n",
    "    opti = Adam(Quantum_net.trainable_params(), learning_rate=lr)  \n",
    "    net = TrainOneStepCell(Quantum_net, opti)\n",
    "    error_min = 1\n",
    "    for j in range(len(train_x)):\n",
    "        net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "        params = abs(Quantum_net.weight.asnumpy())\n",
    "        final_state = []\n",
    "        for k in range(100): # 100 个测试点\n",
    "            sim.reset()\n",
    "            sim.set_qs(eval_x[k])\n",
    "            sim.apply_circuit(circ, params)\n",
    "            final_state.append(sim.get_qs())\n",
    "        error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "        error_min = min(error, error_min)\n",
    "        if error_min < 1e-5:\n",
    "            break\n",
    "    error_min_list.append(error_min)\n",
    "    m_list.append(j)\n",
    "    print(f\"进度: {i+1}/{len(u_mats)} \", 'error_min:', error_min, 'iter_num:', j)\n",
    "    \n",
    "print('mean of iter_num:', np.mean(m_list))\n",
    "print('\\n mean of error is：', np.mean(error_min_list))\n",
    "print('\\nerror_min_list:\\n', error_min_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "1b0150e3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "进度: 1/32  error_min: 2.8627235193479095e-07 iter_num: 948\n",
      "进度: 2/32  error_min: 4.232382480595653e-06 iter_num: 615\n",
      "进度: 3/32  error_min: 9.014042473665107e-06 iter_num: 130\n",
      "进度: 4/32  error_min: 5.9140518340328185e-06 iter_num: 777\n",
      "进度: 5/32  error_min: 5.859669840013737e-06 iter_num: 676\n",
      "进度: 6/32  error_min: 0.0003023491705842485 iter_num: 3999\n",
      "进度: 7/32  error_min: 7.260193236380275e-06 iter_num: 572\n",
      "进度: 8/32  error_min: 7.320080003370144e-06 iter_num: 1911\n",
      "进度: 9/32  error_min: 6.3506511415178934e-06 iter_num: 257\n",
      "进度: 10/32  error_min: 6.61675887925206e-06 iter_num: 492\n",
      "进度: 11/32  error_min: 0.00028807438262234975 iter_num: 3999\n",
      "进度: 12/32  error_min: 7.514627659244155e-06 iter_num: 727\n",
      "进度: 13/32  error_min: 2.0465427778004752e-06 iter_num: 934\n",
      "进度: 14/32  error_min: 5.5684219645302235e-06 iter_num: 234\n",
      "进度: 15/32  error_min: 8.22938415534491e-06 iter_num: 307\n",
      "进度: 16/32  error_min: 7.0235148740271924e-06 iter_num: 942\n",
      "进度: 17/32  error_min: 6.7772918365127666e-06 iter_num: 669\n",
      "进度: 18/32  error_min: 9.771037124073345e-06 iter_num: 1259\n",
      "进度: 19/32  error_min: 4.458040418930942e-06 iter_num: 2058\n",
      "进度: 20/32  error_min: 9.937304922713608e-06 iter_num: 319\n",
      "进度: 21/32  error_min: 2.219499057654062e-06 iter_num: 365\n",
      "进度: 22/32  error_min: 5.711905616712087e-06 iter_num: 428\n",
      "进度: 23/32  error_min: 7.253188669453792e-06 iter_num: 991\n",
      "进度: 24/32  error_min: 6.837451692498497e-06 iter_num: 450\n",
      "进度: 25/32  error_min: 3.374128372368723e-06 iter_num: 790\n",
      "进度: 26/32  error_min: 3.620879980847924e-06 iter_num: 315\n",
      "进度: 27/32  error_min: 9.539619056253557e-06 iter_num: 776\n",
      "进度: 28/32  error_min: 9.715833623524794e-06 iter_num: 937\n",
      "进度: 29/32  error_min: 6.267375187718471e-06 iter_num: 372\n",
      "进度: 30/32  error_min: 8.089388250476226e-06 iter_num: 496\n",
      "进度: 31/32  error_min: 9.746420676748357e-06 iter_num: 519\n",
      "进度: 32/32  error_min: 9.606212850510332e-06 iter_num: 762\n",
      "mean of iter_num: 907.0625\n",
      "\n",
      " mean of error is： 2.4580803881728286e-05\n",
      "\n",
      "error_min_list:\n",
      " [2.8627235193479095e-07, 4.232382480595653e-06, 9.014042473665107e-06, 5.9140518340328185e-06, 5.859669840013737e-06, 0.0003023491705842485, 7.260193236380275e-06, 7.320080003370144e-06, 6.3506511415178934e-06, 6.61675887925206e-06, 0.00028807438262234975, 7.514627659244155e-06, 2.0465427778004752e-06, 5.5684219645302235e-06, 8.22938415534491e-06, 7.0235148740271924e-06, 6.7772918365127666e-06, 9.771037124073345e-06, 4.458040418930942e-06, 9.937304922713608e-06, 2.219499057654062e-06, 5.711905616712087e-06, 7.253188669453792e-06, 6.837451692498497e-06, 3.374128372368723e-06, 3.620879980847924e-06, 9.539619056253557e-06, 9.715833623524794e-06, 6.267375187718471e-06, 8.089388250476226e-06, 9.746420676748357e-06, 9.606212850510332e-06]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi/2\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_0('01').on(0)\n",
    "circ += gate_0('02').on(0)\n",
    "circ += gate_0('03').on(0)\n",
    "circ += gate_0('04').on(0)\n",
    "circ += gate_0('05').on(0)\n",
    "circ += gate_0('06').on(0)\n",
    "circ += gate_0('07').on(0)\n",
    "circ += gate_0('08').on(0)\n",
    "circ += gate_0('09').on(0)\n",
    "\n",
    "circ += gate_0('10').on(0)\n",
    "# circ += gate_0('11').on(0)\n",
    "# circ += gate_0('12').on(0)\n",
    "# circ += gate_0('13').on(0)\n",
    "# circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "\n",
    "error_min_list = [] \n",
    "m_list = []\n",
    "lr = 0.05\n",
    "for i in range(len(u_mats)):\n",
    "    Quantum_net = MQLayer(grad_ops)\n",
    "    opti = Adam(Quantum_net.trainable_params(), learning_rate=lr)  \n",
    "    net = TrainOneStepCell(Quantum_net, opti)\n",
    "    error_min = 1\n",
    "    for j in range(len(train_x)):\n",
    "        net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "        params = abs(Quantum_net.weight.asnumpy())\n",
    "        final_state = []\n",
    "        for k in range(100): # 100 个测试点\n",
    "            sim.reset()\n",
    "            sim.set_qs(eval_x[k])\n",
    "            sim.apply_circuit(circ, params)\n",
    "            final_state.append(sim.get_qs())\n",
    "        error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "        error_min = min(error, error_min)\n",
    "        if error_min < 1e-5:\n",
    "            break\n",
    "    error_min_list.append(error_min)\n",
    "    m_list.append(j)\n",
    "    print(f\"进度: {i+1}/{len(u_mats)} \", 'error_min:', error_min, 'iter_num:', j)\n",
    "    \n",
    "print('mean of iter_num:', np.mean(m_list))\n",
    "print('\\n mean of error is：', np.mean(error_min_list))\n",
    "print('\\nerror_min_list:\\n', error_min_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "81fa8d44",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "进度: 1/32  error_min: 8.84668157219437e-06 iter_num: 400\n",
      "进度: 2/32  error_min: 8.53526304822605e-06 iter_num: 743\n",
      "进度: 3/32  error_min: 6.6813306326407584e-06 iter_num: 1066\n",
      "进度: 4/32  error_min: 7.346130531327155e-06 iter_num: 551\n",
      "进度: 5/32  error_min: 9.388669918286574e-06 iter_num: 474\n",
      "进度: 6/32  error_min: 3.710374978482811e-06 iter_num: 1095\n",
      "进度: 7/32  error_min: 3.617098549568709e-06 iter_num: 446\n",
      "进度: 8/32  error_min: 7.708152753416186e-06 iter_num: 425\n",
      "进度: 9/32  error_min: 1.3573529592525446e-06 iter_num: 546\n",
      "进度: 10/32  error_min: 6.948863480848999e-06 iter_num: 1463\n",
      "进度: 11/32  error_min: 4.811637173918193e-06 iter_num: 652\n",
      "进度: 12/32  error_min: 5.800298286118277e-06 iter_num: 412\n",
      "进度: 13/32  error_min: 9.423738944192017e-06 iter_num: 938\n",
      "进度: 14/32  error_min: 6.572347996280925e-06 iter_num: 538\n",
      "进度: 15/32  error_min: 9.136268624865274e-06 iter_num: 182\n",
      "进度: 16/32  error_min: 9.109511907912093e-06 iter_num: 443\n",
      "进度: 17/32  error_min: 3.791093626359654e-06 iter_num: 464\n",
      "进度: 18/32  error_min: 7.569638206916807e-06 iter_num: 383\n",
      "进度: 19/32  error_min: 3.1626647041260725e-06 iter_num: 3206\n",
      "进度: 20/32  error_min: 6.2484023513054154e-06 iter_num: 926\n",
      "进度: 21/32  error_min: 5.469684745906811e-06 iter_num: 307\n",
      "进度: 22/32  error_min: 7.569461094480978e-06 iter_num: 848\n",
      "进度: 23/32  error_min: 9.707231925726312e-06 iter_num: 1304\n",
      "进度: 24/32  error_min: 7.94133689896448e-06 iter_num: 415\n",
      "进度: 25/32  error_min: 7.034696726360146e-06 iter_num: 1043\n",
      "进度: 26/32  error_min: 9.60085445611547e-06 iter_num: 313\n",
      "进度: 27/32  error_min: 3.944657411381058e-06 iter_num: 1002\n",
      "进度: 28/32  error_min: 7.668871113253317e-06 iter_num: 479\n",
      "进度: 29/32  error_min: 8.298482208513036e-06 iter_num: 578\n",
      "进度: 30/32  error_min: 8.97782759823329e-06 iter_num: 435\n",
      "进度: 31/32  error_min: 5.382917658280917e-07 iter_num: 442\n",
      "进度: 32/32  error_min: 7.669720380354406e-06 iter_num: 871\n",
      "mean of iter_num: 730.9375\n",
      "\n",
      " mean of error is： 6.693332392854884e-06\n",
      "\n",
      "error_min_list:\n",
      " [8.84668157219437e-06, 8.53526304822605e-06, 6.6813306326407584e-06, 7.346130531327155e-06, 9.388669918286574e-06, 3.710374978482811e-06, 3.617098549568709e-06, 7.708152753416186e-06, 1.3573529592525446e-06, 6.948863480848999e-06, 4.811637173918193e-06, 5.800298286118277e-06, 9.423738944192017e-06, 6.572347996280925e-06, 9.136268624865274e-06, 9.109511907912093e-06, 3.791093626359654e-06, 7.569638206916807e-06, 3.1626647041260725e-06, 6.2484023513054154e-06, 5.469684745906811e-06, 7.569461094480978e-06, 9.707231925726312e-06, 7.94133689896448e-06, 7.034696726360146e-06, 9.60085445611547e-06, 3.944657411381058e-06, 7.668871113253317e-06, 8.298482208513036e-06, 8.97782759823329e-06, 5.382917658280917e-07, 7.669720380354406e-06]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi/2\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_0('01').on(0)\n",
    "circ += gate_0('02').on(0)\n",
    "circ += gate_0('03').on(0)\n",
    "circ += gate_0('04').on(0)\n",
    "circ += gate_0('05').on(0)\n",
    "circ += gate_0('06').on(0)\n",
    "circ += gate_0('07').on(0)\n",
    "circ += gate_0('08').on(0)\n",
    "circ += gate_0('09').on(0)\n",
    "\n",
    "circ += gate_0('10').on(0)\n",
    "circ += gate_0('11').on(0)\n",
    "# circ += gate_0('12').on(0)\n",
    "# circ += gate_0('13').on(0)\n",
    "# circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "\n",
    "error_min_list = [] \n",
    "m_list = []\n",
    "lr = 0.05\n",
    "for i in range(len(u_mats)):\n",
    "    Quantum_net = MQLayer(grad_ops)\n",
    "    opti = Adam(Quantum_net.trainable_params(), learning_rate=lr)  \n",
    "    net = TrainOneStepCell(Quantum_net, opti)\n",
    "    error_min = 1\n",
    "    for j in range(len(train_x)):\n",
    "        net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "        params = abs(Quantum_net.weight.asnumpy())\n",
    "        final_state = []\n",
    "        for k in range(100): # 100 个测试点\n",
    "            sim.reset()\n",
    "            sim.set_qs(eval_x[k])\n",
    "            sim.apply_circuit(circ, params)\n",
    "            final_state.append(sim.get_qs())\n",
    "        error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "        error_min = min(error, error_min)\n",
    "        if error_min < 1e-5:\n",
    "            break\n",
    "    error_min_list.append(error_min)\n",
    "    m_list.append(j)\n",
    "    print(f\"进度: {i+1}/{len(u_mats)} \", 'error_min:', error_min, 'iter_num:', j)\n",
    "    \n",
    "print('mean of iter_num:', np.mean(m_list))\n",
    "print('\\n mean of error is：', np.mean(error_min_list))\n",
    "print('\\nerror_min_list:\\n', error_min_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "53974090",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "进度: 1/32  error_min: 8.018508700136096e-06 iter_num: 369\n",
      "进度: 2/32  error_min: 9.569743167125999e-06 iter_num: 293\n",
      "进度: 3/32  error_min: 9.625729032625152e-06 iter_num: 500\n",
      "进度: 4/32  error_min: 9.140834981380408e-06 iter_num: 1125\n",
      "进度: 5/32  error_min: 8.023507596544022e-06 iter_num: 495\n",
      "进度: 6/32  error_min: 8.843959725890471e-06 iter_num: 1013\n",
      "进度: 7/32  error_min: 9.55982539185829e-06 iter_num: 642\n",
      "进度: 8/32  error_min: 8.388071472631431e-06 iter_num: 956\n",
      "进度: 9/32  error_min: 1.76262908790914e-06 iter_num: 1356\n",
      "进度: 10/32  error_min: 4.943593907680288e-06 iter_num: 370\n",
      "进度: 11/32  error_min: 9.305474427123706e-06 iter_num: 439\n",
      "进度: 12/32  error_min: 7.031385551914404e-06 iter_num: 668\n",
      "进度: 13/32  error_min: 9.386661403709695e-06 iter_num: 427\n",
      "进度: 14/32  error_min: 8.75947444112235e-06 iter_num: 306\n",
      "进度: 15/32  error_min: 8.782660634087947e-06 iter_num: 200\n",
      "进度: 16/32  error_min: 3.01296733129508e-06 iter_num: 1809\n",
      "进度: 17/32  error_min: 6.078597599934454e-06 iter_num: 1315\n",
      "进度: 18/32  error_min: 7.49291781698691e-06 iter_num: 207\n",
      "进度: 19/32  error_min: 4.432748758165239e-06 iter_num: 341\n",
      "进度: 20/32  error_min: 4.831270035476898e-06 iter_num: 1339\n",
      "进度: 21/32  error_min: 5.644165695595227e-06 iter_num: 791\n",
      "进度: 22/32  error_min: 9.18317679188263e-06 iter_num: 613\n",
      "进度: 23/32  error_min: 7.634810477608056e-06 iter_num: 500\n",
      "进度: 24/32  error_min: 7.77262418905078e-06 iter_num: 835\n",
      "进度: 25/32  error_min: 6.791357856750224e-06 iter_num: 272\n",
      "进度: 26/32  error_min: 8.897418703024407e-06 iter_num: 974\n",
      "进度: 27/32  error_min: 9.494999698933526e-06 iter_num: 790\n",
      "进度: 28/32  error_min: 7.085587535593518e-06 iter_num: 178\n",
      "进度: 29/32  error_min: 8.065867681761318e-06 iter_num: 694\n",
      "进度: 30/32  error_min: 8.809990964864234e-06 iter_num: 464\n",
      "进度: 31/32  error_min: 9.379252957852913e-06 iter_num: 215\n",
      "进度: 32/32  error_min: 6.616657385438707e-06 iter_num: 1209\n",
      "mean of iter_num: 678.28125\n",
      "\n",
      " mean of error is： 7.5739522188110475e-06\n",
      "\n",
      "error_min_list:\n",
      " [8.018508700136096e-06, 9.569743167125999e-06, 9.625729032625152e-06, 9.140834981380408e-06, 8.023507596544022e-06, 8.843959725890471e-06, 9.55982539185829e-06, 8.388071472631431e-06, 1.76262908790914e-06, 4.943593907680288e-06, 9.305474427123706e-06, 7.031385551914404e-06, 9.386661403709695e-06, 8.75947444112235e-06, 8.782660634087947e-06, 3.01296733129508e-06, 6.078597599934454e-06, 7.49291781698691e-06, 4.432748758165239e-06, 4.831270035476898e-06, 5.644165695595227e-06, 9.18317679188263e-06, 7.634810477608056e-06, 7.77262418905078e-06, 6.791357856750224e-06, 8.897418703024407e-06, 9.494999698933526e-06, 7.085587535593518e-06, 8.065867681761318e-06, 8.809990964864234e-06, 9.379252957852913e-06, 6.616657385438707e-06]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi/2\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_0('01').on(0)\n",
    "circ += gate_0('02').on(0)\n",
    "circ += gate_0('03').on(0)\n",
    "circ += gate_0('04').on(0)\n",
    "circ += gate_0('05').on(0)\n",
    "circ += gate_0('06').on(0)\n",
    "circ += gate_0('07').on(0)\n",
    "circ += gate_0('08').on(0)\n",
    "circ += gate_0('09').on(0)\n",
    "\n",
    "circ += gate_0('10').on(0)\n",
    "circ += gate_0('11').on(0)\n",
    "circ += gate_0('12').on(0)\n",
    "# circ += gate_0('13').on(0)\n",
    "# circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "\n",
    "error_min_list = [] \n",
    "m_list = []\n",
    "lr = 0.05\n",
    "for i in range(len(u_mats)):\n",
    "    Quantum_net = MQLayer(grad_ops)\n",
    "    opti = Adam(Quantum_net.trainable_params(), learning_rate=lr)  \n",
    "    net = TrainOneStepCell(Quantum_net, opti)\n",
    "    error_min = 1\n",
    "    for j in range(len(train_x)):\n",
    "        net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "        params = abs(Quantum_net.weight.asnumpy())\n",
    "        final_state = []\n",
    "        for k in range(100): # 100 个测试点\n",
    "            sim.reset()\n",
    "            sim.set_qs(eval_x[k])\n",
    "            sim.apply_circuit(circ, params)\n",
    "            final_state.append(sim.get_qs())\n",
    "        error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "        error_min = min(error, error_min)\n",
    "        if error_min < 1e-5:\n",
    "            break\n",
    "    error_min_list.append(error_min)\n",
    "    m_list.append(j)\n",
    "    print(f\"进度: {i+1}/{len(u_mats)} \", 'error_min:', error_min, 'iter_num:', j)\n",
    "    \n",
    "print('mean of iter_num:', np.mean(m_list))\n",
    "print('\\n mean of error is：', np.mean(error_min_list))\n",
    "print('\\nerror_min_list:\\n', error_min_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "69b0a610",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "进度: 1/32  error_min: 2.9176593930868577e-06 iter_num: 492\n",
      "进度: 2/32  error_min: 9.707463507591108e-06 iter_num: 483\n",
      "进度: 3/32  error_min: 5.363244803491263e-06 iter_num: 329\n",
      "进度: 4/32  error_min: 7.100093438849875e-06 iter_num: 683\n",
      "进度: 5/32  error_min: 7.513125426128475e-06 iter_num: 611\n",
      "进度: 6/32  error_min: 4.730430267718688e-06 iter_num: 1899\n",
      "进度: 7/32  error_min: 5.264405637417369e-06 iter_num: 253\n",
      "进度: 8/32  error_min: 7.982269009110254e-06 iter_num: 906\n",
      "进度: 9/32  error_min: 8.675682383163519e-06 iter_num: 776\n",
      "进度: 10/32  error_min: 7.610013475600752e-06 iter_num: 812\n",
      "进度: 11/32  error_min: 8.372992603478124e-06 iter_num: 1511\n",
      "进度: 12/32  error_min: 7.4001078621543925e-06 iter_num: 522\n",
      "进度: 13/32  error_min: 3.530089060066466e-06 iter_num: 1650\n",
      "进度: 14/32  error_min: 9.194134762302575e-06 iter_num: 727\n",
      "进度: 15/32  error_min: 9.594590660078062e-06 iter_num: 290\n",
      "进度: 16/32  error_min: 4.794364383275962e-07 iter_num: 847\n",
      "进度: 17/32  error_min: 8.44556339429925e-06 iter_num: 623\n",
      "进度: 18/32  error_min: 6.848379944468519e-06 iter_num: 523\n",
      "进度: 19/32  error_min: 7.604210471634509e-06 iter_num: 424\n",
      "进度: 20/32  error_min: 8.729554610509282e-06 iter_num: 1000\n",
      "进度: 21/32  error_min: 9.648422962138525e-06 iter_num: 1662\n",
      "进度: 22/32  error_min: 7.812833176079614e-06 iter_num: 156\n",
      "进度: 23/32  error_min: 5.64170077921311e-06 iter_num: 1593\n",
      "进度: 24/32  error_min: 9.647765888853854e-06 iter_num: 757\n",
      "进度: 25/32  error_min: 7.3764995380809495e-06 iter_num: 421\n",
      "进度: 26/32  error_min: 9.61633218865554e-06 iter_num: 1031\n",
      "进度: 27/32  error_min: 8.820672522280582e-06 iter_num: 1057\n",
      "进度: 28/32  error_min: 9.80956314577952e-06 iter_num: 607\n",
      "进度: 29/32  error_min: 9.203713813188408e-06 iter_num: 820\n",
      "进度: 30/32  error_min: 8.281062910286963e-06 iter_num: 370\n",
      "进度: 31/32  error_min: 3.1224198226986744e-06 iter_num: 281\n",
      "进度: 32/32  error_min: 5.516241199932104e-06 iter_num: 560\n",
      "mean of iter_num: 771.125\n",
      "\n",
      " mean of error is： 7.236271096770774e-06\n",
      "\n",
      "error_min_list:\n",
      " [2.9176593930868577e-06, 9.707463507591108e-06, 5.363244803491263e-06, 7.100093438849875e-06, 7.513125426128475e-06, 4.730430267718688e-06, 5.264405637417369e-06, 7.982269009110254e-06, 8.675682383163519e-06, 7.610013475600752e-06, 8.372992603478124e-06, 7.4001078621543925e-06, 3.530089060066466e-06, 9.194134762302575e-06, 9.594590660078062e-06, 4.794364383275962e-07, 8.44556339429925e-06, 6.848379944468519e-06, 7.604210471634509e-06, 8.729554610509282e-06, 9.648422962138525e-06, 7.812833176079614e-06, 5.64170077921311e-06, 9.647765888853854e-06, 7.3764995380809495e-06, 9.61633218865554e-06, 8.820672522280582e-06, 9.80956314577952e-06, 9.203713813188408e-06, 8.281062910286963e-06, 3.1224198226986744e-06, 5.516241199932104e-06]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi/2\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_0('01').on(0)\n",
    "circ += gate_0('02').on(0)\n",
    "circ += gate_0('03').on(0)\n",
    "circ += gate_0('04').on(0)\n",
    "circ += gate_0('05').on(0)\n",
    "circ += gate_0('06').on(0)\n",
    "circ += gate_0('07').on(0)\n",
    "circ += gate_0('08').on(0)\n",
    "circ += gate_0('09').on(0)\n",
    "\n",
    "circ += gate_0('10').on(0)\n",
    "circ += gate_0('11').on(0)\n",
    "circ += gate_0('12').on(0)\n",
    "circ += gate_0('13').on(0)\n",
    "# circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "\n",
    "error_min_list = [] \n",
    "m_list = []\n",
    "lr = 0.05\n",
    "for i in range(len(u_mats)):\n",
    "    Quantum_net = MQLayer(grad_ops)\n",
    "    opti = Adam(Quantum_net.trainable_params(), learning_rate=lr)  \n",
    "    net = TrainOneStepCell(Quantum_net, opti)\n",
    "    error_min = 1\n",
    "    for j in range(len(train_x)):\n",
    "        net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "        params = abs(Quantum_net.weight.asnumpy())\n",
    "        final_state = []\n",
    "        for k in range(100): # 100 个测试点\n",
    "            sim.reset()\n",
    "            sim.set_qs(eval_x[k])\n",
    "            sim.apply_circuit(circ, params)\n",
    "            final_state.append(sim.get_qs())\n",
    "        error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "        error_min = min(error, error_min)\n",
    "        if error_min < 1e-5:\n",
    "            break\n",
    "    error_min_list.append(error_min)\n",
    "    m_list.append(j)\n",
    "    print(f\"进度: {i+1}/{len(u_mats)} \", 'error_min:', error_min, 'iter_num:', j)\n",
    "    \n",
    "print('mean of iter_num:', np.mean(m_list))\n",
    "print('\\n mean of error is：', np.mean(error_min_list))\n",
    "print('\\nerror_min_list:\\n', error_min_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "30c30cbc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "进度: 1/32  error_min: 9.6121552672912e-06 iter_num: 641\n",
      "进度: 2/32  error_min: 5.035774005013316e-06 iter_num: 560\n",
      "进度: 3/32  error_min: 9.160490345383465e-06 iter_num: 933\n",
      "进度: 4/32  error_min: 9.085394180208262e-06 iter_num: 737\n",
      "进度: 5/32  error_min: 7.443008824603581e-06 iter_num: 671\n",
      "进度: 6/32  error_min: 5.793386794405997e-06 iter_num: 450\n",
      "进度: 7/32  error_min: 9.061412234334654e-06 iter_num: 1016\n",
      "进度: 8/32  error_min: 7.558411317720726e-06 iter_num: 1030\n",
      "进度: 9/32  error_min: 7.159125578692915e-06 iter_num: 626\n",
      "进度: 10/32  error_min: 2.178361631743897e-06 iter_num: 1784\n",
      "进度: 11/32  error_min: 9.457726972472713e-06 iter_num: 472\n",
      "进度: 12/32  error_min: 4.328448272805652e-06 iter_num: 721\n",
      "进度: 13/32  error_min: 7.762338349093234e-06 iter_num: 615\n",
      "进度: 14/32  error_min: 6.763171499946097e-06 iter_num: 598\n",
      "进度: 15/32  error_min: 2.267615826112568e-06 iter_num: 607\n",
      "进度: 16/32  error_min: 9.644420654653096e-06 iter_num: 695\n",
      "进度: 17/32  error_min: 9.079189811633803e-06 iter_num: 140\n",
      "进度: 18/32  error_min: 2.5569784068979473e-06 iter_num: 537\n",
      "进度: 19/32  error_min: 4.656076594833358e-06 iter_num: 479\n",
      "进度: 20/32  error_min: 6.444471432276444e-06 iter_num: 464\n",
      "进度: 21/32  error_min: 6.123502388044599e-06 iter_num: 140\n",
      "进度: 22/32  error_min: 6.5933378695648415e-06 iter_num: 824\n",
      "进度: 23/32  error_min: 6.983683518368977e-06 iter_num: 292\n",
      "进度: 24/32  error_min: 4.356026078400355e-06 iter_num: 698\n",
      "进度: 25/32  error_min: 5.984916992107792e-06 iter_num: 304\n",
      "进度: 26/32  error_min: 5.537144853073883e-06 iter_num: 789\n",
      "进度: 27/32  error_min: 2.6471480433221117e-06 iter_num: 631\n",
      "进度: 28/32  error_min: 9.470177131820634e-06 iter_num: 350\n",
      "进度: 29/32  error_min: 3.3516792652399374e-06 iter_num: 168\n",
      "进度: 30/32  error_min: 1.9384540436151454e-06 iter_num: 697\n",
      "进度: 31/32  error_min: 5.281180478156067e-06 iter_num: 359\n",
      "进度: 32/32  error_min: 9.82988480302538e-06 iter_num: 462\n",
      "mean of iter_num: 609.0625\n",
      "\n",
      " mean of error is： 6.348284170776958e-06\n",
      "\n",
      "error_min_list:\n",
      " [9.6121552672912e-06, 5.035774005013316e-06, 9.160490345383465e-06, 9.085394180208262e-06, 7.443008824603581e-06, 5.793386794405997e-06, 9.061412234334654e-06, 7.558411317720726e-06, 7.159125578692915e-06, 2.178361631743897e-06, 9.457726972472713e-06, 4.328448272805652e-06, 7.762338349093234e-06, 6.763171499946097e-06, 2.267615826112568e-06, 9.644420654653096e-06, 9.079189811633803e-06, 2.5569784068979473e-06, 4.656076594833358e-06, 6.444471432276444e-06, 6.123502388044599e-06, 6.5933378695648415e-06, 6.983683518368977e-06, 4.356026078400355e-06, 5.984916992107792e-06, 5.537144853073883e-06, 2.6471480433221117e-06, 9.470177131820634e-06, 3.3516792652399374e-06, 1.9384540436151454e-06, 5.281180478156067e-06, 9.82988480302538e-06]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi/2\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_0('01').on(0)\n",
    "circ += gate_0('02').on(0)\n",
    "circ += gate_0('03').on(0)\n",
    "circ += gate_0('04').on(0)\n",
    "circ += gate_0('05').on(0)\n",
    "circ += gate_0('06').on(0)\n",
    "circ += gate_0('07').on(0)\n",
    "circ += gate_0('08').on(0)\n",
    "circ += gate_0('09').on(0)\n",
    "\n",
    "circ += gate_0('10').on(0)\n",
    "circ += gate_0('11').on(0)\n",
    "circ += gate_0('12').on(0)\n",
    "circ += gate_0('13').on(0)\n",
    "circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "\n",
    "error_min_list = [] \n",
    "m_list = []\n",
    "lr = 0.05\n",
    "for i in range(len(u_mats)):\n",
    "    Quantum_net = MQLayer(grad_ops)\n",
    "    opti = Adam(Quantum_net.trainable_params(), learning_rate=lr)  \n",
    "    net = TrainOneStepCell(Quantum_net, opti)\n",
    "    error_min = 1\n",
    "    for j in range(len(train_x)):\n",
    "        net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "        params = abs(Quantum_net.weight.asnumpy())\n",
    "        final_state = []\n",
    "        for k in range(100): # 100 个测试点\n",
    "            sim.reset()\n",
    "            sim.set_qs(eval_x[k])\n",
    "            sim.apply_circuit(circ, params)\n",
    "            final_state.append(sim.get_qs())\n",
    "        error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "        error_min = min(error, error_min)\n",
    "        if error_min < 1e-5:\n",
    "            break\n",
    "    error_min_list.append(error_min)\n",
    "    m_list.append(j)\n",
    "    print(f\"进度: {i+1}/{len(u_mats)} \", 'error_min:', error_min, 'iter_num:', j)\n",
    "    \n",
    "print('mean of iter_num:', np.mean(m_list))\n",
    "print('\\n mean of error is：', np.mean(error_min_list))\n",
    "print('\\nerror_min_list:\\n', error_min_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "6220ec94",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "进度: 1/32  error_min: 3.4253672188677697e-06 iter_num: 694\n",
      "进度: 2/32  error_min: 4.224228158045129e-06 iter_num: 455\n",
      "进度: 3/32  error_min: 7.233869388723058e-06 iter_num: 264\n",
      "进度: 4/32  error_min: 2.698849282833926e-06 iter_num: 904\n",
      "进度: 5/32  error_min: 5.809239904452923e-06 iter_num: 399\n",
      "进度: 6/32  error_min: 7.017408601206476e-06 iter_num: 395\n",
      "进度: 7/32  error_min: 4.255298976962862e-06 iter_num: 305\n",
      "进度: 8/32  error_min: 7.315566393994999e-06 iter_num: 713\n",
      "进度: 9/32  error_min: 6.157588105293321e-06 iter_num: 277\n",
      "进度: 10/32  error_min: 2.958569227939911e-06 iter_num: 1035\n",
      "进度: 11/32  error_min: 9.985108710863777e-06 iter_num: 465\n",
      "进度: 12/32  error_min: 8.513927841957702e-06 iter_num: 320\n",
      "进度: 13/32  error_min: 8.585133563054903e-06 iter_num: 789\n",
      "进度: 14/32  error_min: 4.4132685222963985e-06 iter_num: 262\n",
      "进度: 15/32  error_min: 6.71784613215376e-06 iter_num: 454\n",
      "进度: 16/32  error_min: 7.369638270859902e-06 iter_num: 373\n",
      "进度: 17/32  error_min: 4.720847349370949e-06 iter_num: 1115\n",
      "进度: 18/32  error_min: 7.595915377689444e-06 iter_num: 231\n",
      "进度: 19/32  error_min: 1.4413811098012985e-06 iter_num: 381\n",
      "进度: 20/32  error_min: 6.286414453438027e-06 iter_num: 1915\n",
      "进度: 21/32  error_min: 4.94923076987952e-06 iter_num: 553\n",
      "进度: 22/32  error_min: 6.842691649300292e-06 iter_num: 174\n",
      "进度: 23/32  error_min: 9.64763239785782e-06 iter_num: 411\n",
      "进度: 24/32  error_min: 3.482331999316024e-06 iter_num: 647\n",
      "进度: 25/32  error_min: 8.016561748092066e-06 iter_num: 581\n",
      "进度: 26/32  error_min: 6.835025000873074e-06 iter_num: 241\n",
      "进度: 27/32  error_min: 5.476691182781934e-06 iter_num: 508\n",
      "进度: 28/32  error_min: 7.040365393451431e-06 iter_num: 130\n",
      "进度: 29/32  error_min: 6.67395022002637e-06 iter_num: 403\n",
      "进度: 30/32  error_min: 6.772999024740045e-06 iter_num: 1455\n",
      "进度: 31/32  error_min: 7.620959827203677e-06 iter_num: 175\n",
      "进度: 32/32  error_min: 8.351499654724037e-06 iter_num: 306\n",
      "mean of iter_num: 541.5625\n",
      "\n",
      " mean of error is： 6.201106420564151e-06\n",
      "\n",
      "error_min_list:\n",
      " [3.4253672188677697e-06, 4.224228158045129e-06, 7.233869388723058e-06, 2.698849282833926e-06, 5.809239904452923e-06, 7.017408601206476e-06, 4.255298976962862e-06, 7.315566393994999e-06, 6.157588105293321e-06, 2.958569227939911e-06, 9.985108710863777e-06, 8.513927841957702e-06, 8.585133563054903e-06, 4.4132685222963985e-06, 6.71784613215376e-06, 7.369638270859902e-06, 4.720847349370949e-06, 7.595915377689444e-06, 1.4413811098012985e-06, 6.286414453438027e-06, 4.94923076987952e-06, 6.842691649300292e-06, 9.64763239785782e-06, 3.482331999316024e-06, 8.016561748092066e-06, 6.835025000873074e-06, 5.476691182781934e-06, 7.040365393451431e-06, 6.67395022002637e-06, 6.772999024740045e-06, 7.620959827203677e-06, 8.351499654724037e-06]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi/2\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_0('01').on(0)\n",
    "circ += gate_0('02').on(0)\n",
    "circ += gate_0('03').on(0)\n",
    "circ += gate_0('04').on(0)\n",
    "circ += gate_0('05').on(0)\n",
    "circ += gate_0('06').on(0)\n",
    "circ += gate_0('07').on(0)\n",
    "circ += gate_0('08').on(0)\n",
    "circ += gate_0('09').on(0)\n",
    "\n",
    "circ += gate_0('10').on(0)\n",
    "circ += gate_0('11').on(0)\n",
    "circ += gate_0('12').on(0)\n",
    "circ += gate_0('13').on(0)\n",
    "circ += gate_0('14').on(0)\n",
    "circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "\n",
    "error_min_list = [] \n",
    "m_list = []\n",
    "lr = 0.05\n",
    "for i in range(len(u_mats)):\n",
    "    Quantum_net = MQLayer(grad_ops)\n",
    "    opti = Adam(Quantum_net.trainable_params(), learning_rate=lr)  \n",
    "    net = TrainOneStepCell(Quantum_net, opti)\n",
    "    error_min = 1\n",
    "    for j in range(len(train_x)):\n",
    "        net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "        params = abs(Quantum_net.weight.asnumpy())\n",
    "        final_state = []\n",
    "        for k in range(100): # 100 个测试点\n",
    "            sim.reset()\n",
    "            sim.set_qs(eval_x[k])\n",
    "            sim.apply_circuit(circ, params)\n",
    "            final_state.append(sim.get_qs())\n",
    "        error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "        error_min = min(error, error_min)\n",
    "        if error_min < 1e-5:\n",
    "            break\n",
    "    error_min_list.append(error_min)\n",
    "    m_list.append(j)\n",
    "    print(f\"进度: {i+1}/{len(u_mats)} \", 'error_min:', error_min, 'iter_num:', j)\n",
    "    \n",
    "print('mean of iter_num:', np.mean(m_list))\n",
    "print('\\n mean of error is：', np.mean(error_min_list))\n",
    "print('\\nerror_min_list:\\n', error_min_list)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
